﻿using AuthCenter_HuangJingtao.Domain;
using AuthCenter_HuangJingtao.ErrorCode;
using AuthCenter_HuangJingtao.Infrastructure.Imterfaces;
using AuthCenter_HuangJingtao.Read.Api.Application.Command;
using AuthCenter_HuangJingtao.Read.Api.Dto;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace AuthCenter_HuangJingtao.Read.Api.Application.CommandHandler
{
    public class UpdateAppPermissionCommandHandler : IRequestHandler<UpdateAppPermissionCommand, ApiResult<int>>
    {
        IBaseReponsitory<Roles> Roles;
        IBaseReponsitory<App> Apps;
        IBaseReponsitory<RoleApp> RoleApp;

        public UpdateAppPermissionCommandHandler(IBaseReponsitory<Roles> Roles, IBaseReponsitory<App> Apps, IBaseReponsitory<RoleApp> RoleApp)
        {
            this.Roles = Roles;
            this.Apps = Apps;
            this.RoleApp = RoleApp;
        }

        public async Task<ApiResult<int>> Handle(UpdateAppPermissionCommand request, CancellationToken cancellationToken)
        {
            var item = Apps.GetQuery().Where(c => c.App_Id == request.App_Id && !c.App_IsDel).FirstOrDefault();
            var arr = item.Role_ArrId.Split(',').Select(int.Parse).ToArray();
            foreach (int role_id in arr)
            {
                if (role_id == request.Role_Id)
                {
                    //item.Role_ArrId的值[1,2,3]内移除role_id并去除","
                    item.Role_ArrId = string.Join(",", arr.Where(c => c != role_id));
                }
            }
            if (item.Role_ArrId.Length == 0)
            {
                item.Role_ArrId = "0";
            }
            await Apps.UpdateAsync(item);
            return new ApiResult<int>
            {
                Code = ApiEnum.Success,
                Message = "修改成功",
                Data = 1

            };
        }
    }
}
